/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Operations.Algebra;

import Operations.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.*;

/**
 *
 * @author littlechild
 */
public class OpCptWith {

    public BufferedImage operate(BufferedImage image, String filename,boolean isAdd) {
        try {
            int rgbmask=0xffffff;
            BufferedImage image2 = ImageIO.read(new File(filename));
            int width=(image2.getWidth()>image.getWidth()) ? image.getWidth(): image2.getWidth();
            int height=(image2.getHeight()>image.getHeight()) ? image.getHeight(): image2.getHeight();
            BufferedImage returnImage=new BufferedImage(width,height,image.getType());
            if(isAdd) {
                for(int i=0;i!=returnImage.getWidth();++i) {
                    for (int j=0;j!=returnImage.getHeight();++j) {
                        int rgb1=(image.getRGB(i, j)&rgbmask);
                        int rgb2=(image2.getRGB(i, j)&rgbmask);
                        int red=(((rgb1>>>16)&0xff)+((rgb2>>>16)&0xff))/2;
                        int green=(((rgb1>>>8)&0xff)+((rgb2>>>8)&0xff))/2;
                        int blue=(((rgb1)&0xff)+((rgb2)&0xff))/2;
                        returnImage.setRGB(i,j,(red<<16)|(green<<8)|blue);
                    }
                }
            }else {
                for(int i=0;i!=returnImage.getWidth();++i) {
                    for (int j=0;j!=returnImage.getHeight();++j) {
                        int rgb1=(image.getRGB(i, j)&rgbmask);
                        int rgb2=(image2.getRGB(i, j)&rgbmask);
                        //int red=(0xff+((rgb1>>>16)&0xff)-((rgb2>>>16)&0xff))/2;
                        //int green=(0xff+((rgb1>>>8)&0xff)-((rgb2>>>8)&0xff))/2;
                        //int blue=(0xff+((rgb1)&0xff)-((rgb2)&0xff))/2;
                        int red=((rgb1>>>16)&0xff)-((rgb2>>>16)&0xff);
                        red=(red >0 ) ? red : 0;
                        int green=((rgb1>>>8)&0xff)-((rgb2>>>8)&0xff);
                        green=(green >0 ) ? green :0;
                        int blue=((rgb1)&0xff)-((rgb2)&0xff);
                        blue=(blue>0) ? blue : 0;
                        returnImage.setRGB(i,j,(red<<16)|(green<<8)|blue);
                    }
                }
            }
            return returnImage;
        } catch (IOException ex) {
            Logger.getLogger(OpCptWith.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

}
